package com.tommy.jiami.ui.dialog;

import android.os.*;
import android.view.*;
import android.widget.*;
import com.tommy.jiami.*;
import com.tommy.jiami.db.*;
import android.content.*;
import com.tommy.jiami.utils.*;
import android.database.*;
import android.app.*;

public class AddPassageDialog extends BaseDialogFragment
{
	int id=-1;
	EditText title,detail;
	DBHelper helper;
	boolean isCover=false;

	public AddPassageDialog(int id)
	{
		this.id = id;
	}
	
	public AddPassageDialog(){
		
	}
	
	@Override
	public View getContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		getDialog().setTitle(id==-1?R.string.add_passage:R.string.update_passage);
		getDialog().setCancelable(false);
		getDialog().setCanceledOnTouchOutside(false);
		View view=inflater.inflate(R.layout.dialog_add_passage,null);
		title=(EditText)view.findViewById(R.id.addpassage_title);
		detail=(EditText)view.findViewById(R.id.addpassage_detail);
		helper=new DBHelper(getActivity(),"tommydb",1);
		if(id!=-1){
			try
			{
				String userPwd=Utils.getUserPassword();
				Cursor c=helper.getReadableDatabase().rawQuery("select * from passage where _id=?", new String[]{id + ""});
				c.moveToFirst();
				String titleStr=Crypt.decryptString(c.getString(c.getColumnIndex("title")),userPwd);
				String detailStr=Crypt.decryptString(c.getString(c.getColumnIndex("detail")), userPwd);
				title.setText(titleStr);
				detail.setText(detailStr);
			}
			catch (Exception e)
			{Utils.showToast(e.toString());}

		}
		
		return view;
	}

	@Override
	public void show(FragmentManager manager, String tag)
	{
		super.show(manager, tag);
	}
	
	@Override
	protected void onPositiveButtonClick()
	{
		try
		{
			String userPwd=Utils.getUserPassword();
			String titleStr=Crypt.encryptString(title.getText().toString(), userPwd);
			String detailStr=Crypt.encryptString(detail.getText().toString(), userPwd);
			if(id==-1){
				helper.getWritableDatabase().execSQL("insert into passage values(null,?,?)",
				new Object[]{titleStr,detailStr});
			}else{
				helper.getWritableDatabase().execSQL("update passage set title=?,detail=? where _id=?",
				new Object[]{titleStr,detailStr,id});
			}
			
			getActivity().sendBroadcast(new Intent(Constants.ACTION_UPDATE_PASSAGE));
		}
		catch (Exception e)
		{}

		super.onPositiveButtonClick();
	}
	
}
